//
//  NetWorkTools.m
//  NewsBoard
//
//  Created by apple on 16/1/30.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "NetWorkTools.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>


@implementation NetWorkTools

static NSString * const NewsBoardBaseURLString = @"http://114.55.31.187:8082/HttpGet.aspx";

static NetWorkTools *_instance;
+ (instancetype)sharedNetWorkTools{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:NewsBoardBaseURLString]];
        
        _instance.requestSerializer = [AFJSONRequestSerializer serializer];
        
        _instance.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    });
    
    return _instance;
}


- (void)objectWithURLDict:(id )URLDict AndMenthodName:(NSString *)MenthodNameString completeBlock:(CompleteBlock)completeBlock{

    NSString *menthodParams;
    if ([URLDict isKindOfClass:[NSArray class]]) {
        menthodParams = [self arrayToJson:URLDict];
    }else{
        menthodParams = [self dictionaryToJson:URLDict];
    }
    
    
    /**
     *  参数转Json转移字符串
     */
    
    
    NSString *sign = [self getSha1String:[NSString stringWithFormat:@"%@abc_1qazxsw@",MenthodNameString]];
    
    // 验证sign
//    NSLog(@"%@",sign);
    
    NSDictionary *params = @{
                             @"MenthodName":[NSString stringWithFormat:@"%@",MenthodNameString],
                             @"MenthodParms":[NSString stringWithFormat:@"%@",menthodParams],
                             @"Sign":[NSString stringWithFormat:@"%@",sign]
                             };
    // 验证字典转Json转移字符串
//    NSLog(@"%@",params);
    
    [self POST:NewsBoardBaseURLString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id result = [self toArrayOrNSDictionary:responseObject];
        
        if (completeBlock) {
            completeBlock(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

- (void)OtherobjectWithURLDict:(NSDictionary *)URLDict AndMenthodName:(NSString *)MenthodNameString completeBlock:(CompleteBlock)completeBlock{
    
    /**
     //9568F4B2ED27BD2E3BE1A1C488669658A508B626
     *  参数转Json转移字符串
     */
    NSString *menthodParams = [self dictionaryToJson:URLDict];
    
    NSString *sign = [self getSha1String:[NSString stringWithFormat:@"%@abc_1qazxsw@",MenthodNameString]];
    sign = [sign uppercaseString];
    
    // 验证sign
    //    NSLog(@"%@",sign);
    
    NSDictionary *params = @{
                             @"MenthodName":[NSString stringWithFormat:@"%@",MenthodNameString],
                             @"MenthodParms":[NSString stringWithFormat:@"%@",menthodParams],
                             @"Sign":[NSString stringWithFormat:@"%@",sign]
                             };
    // 验证字典转Json转移字符串
    //    NSLog(@"%@",params);
    
    [self POST:@"http://114.55.31.187:61211/Ticket.ashx" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
     //   NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id result = [self toArrayOrNSDictionary:responseObject];
        
        if (completeBlock) {
            completeBlock(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"errorerror%@",error);
    }];
}


- (void)ShopCarobjectWithURLDict:(id )URLDict AndMenthodName:(NSString *)MenthodNameString completeBlock:(CompleteBlock)completeBlock{
    
    NSString *menthodParams;
    if ([URLDict isKindOfClass:[NSArray class]]) {
        menthodParams = [self arrayToJson:URLDict];
    }else{
        menthodParams = [self dictionaryToJson:URLDict];
    }
    
    
    NSString *sign = [self getSha1String:[NSString stringWithFormat:@"%@abc_1qazxsw@",MenthodNameString]];
    sign = [sign uppercaseString];
    
    // 验证sign
    //    NSLog(@"%@",sign);
        NSDictionary *params = @{
                             @"MenthodName":[NSString stringWithFormat:@"%@",MenthodNameString],
                             @"MenthodParms":[NSString stringWithFormat:@"%@",menthodParams],
                             @"Sign":[NSString stringWithFormat:@"%@",sign]
                             };
    // 验证字典转Json转移字符串
    //    NSLog(@"%@",params);
    
    [self POST:@"http://192.168.30.254:8090/httpGet.aspx" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        //   NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id result = [self toArrayOrNSDictionary:responseObject];
        
        if (completeBlock) {
            completeBlock(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"errorerror%@",error);
    }];
}




/**
 *  字典转Json转义字符串
 */
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *hasNStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *endeStr = [hasNStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    endeStr = [endeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return endeStr;
}
/**
 *  数组转Json转义字符串
 */

- (NSString*)arrayToJson:(NSArray *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *hasNStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *endeStr = [hasNStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    endeStr = [endeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return endeStr;
}

/**
 *  加密方法
 */
- (NSString *)getSha1String:(NSString *)srcString{
    const char *cstr = [srcString cStringUsingEncoding:NSUTF8StringEncoding];
    //    const char *cstr = [srcString ];
    NSData *data = [NSData dataWithBytes:cstr length:srcString.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];
    
    for(int i =0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}

/**
 *  返回数据反序列化
 */
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

/**
 *  字符串转字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json字典解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

/**
 *  字符串转数组
 */
+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        if(err) {
   //     NSLog(@"json数组解析失败：%@",err);
        return nil;
    }
    return arr;
}


@end
